package com.neusoft.Shixun.util;

import com.neusoft.Shixun.service.RedisService;
import com.neusoft.Shixun.service.impl.RedisServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 直接放行 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 获取请求头中的Authorization字段
        String authHeader = request.getHeader("Authorization");
        System.out.println(request);
        System.out.println(authHeader);
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            // 提取JWT令牌
            String token = authHeader.substring(7); // 去掉"Bearer "前缀
            System.out.println(token);

            // 检查令牌是否在黑名单中
            if (redisService.isTokenBlacklisted(token)) {
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "Token is blacklisted");
                return false;
            }

            try {
                // 验证令牌
                JwtUtil.verifyToken(token);
                return true; // 令牌有效，继续处理请求
            } catch (Exception e) {
                // 令牌无效，返回401 Unauthorized
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid or expired token");
                return false;
            }
        } else {
            // 没有提供令牌，返回401 Unauthorized
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Missing or invalid Authorization header");
            return false;
        }
    }
}